package com.daxia.wxpay.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

import com.daxia.ogmall.exception.BizException;
import com.daxia.ogmall.web.controller.BaseController;
import com.daxia.wxpay.common.Signature;
import com.daxia.wxpay.common.Util;
import com.daxia.wxpay.common.XMLParser;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

@Controller
@RequestMapping(value = "/wxpay")
public class WxPayAsynNotifyController extends BaseController {
    private static Logger logger = Logger.getLogger(WxPayAsynNotifyController.class);
    private static String successXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    
    //@Autowired
    //private OnlinePayService onlinePayService;
    
    /**
     * 绀轰緥濡備笅锛氳鍙傝�� https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_7&index=3
     * <pre>
     *  <xml>
   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
   <attach><![CDATA[鏀粯娴嬭瘯]]></attach>
   <bank_type><![CDATA[CFT]]></bank_type>
   <fee_type><![CDATA[CNY]]></fee_type>
   <is_subscribe><![CDATA[Y]]></is_subscribe>
   <mch_id><![CDATA[10000100]]></mch_id>
   <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
   <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
   <out_trade_no><![CDATA[1409811653]]></out_trade_no>
   <result_code><![CDATA[SUCCESS]]></result_code>
   <return_code><![CDATA[SUCCESS]]></return_code>
   <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
   <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
   <time_end><![CDATA[20140903131540]]></time_end>
   <total_fee>1</total_fee>
   <trade_type><![CDATA[JSAPI]]></trade_type>
   <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
</xml> 

鐪熷疄鏁版嵁锛�
notify, xml: 
<xml><appid><![CDATA[wx28c153b9a6f56a9b]]></appid>
<attach><![CDATA[閸欏倷绗屽ú璇插З]]></attach>
<bank_type><![CDATA[CFT]]></bank_type>
<cash_fee><![CDATA[4]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[1243213602]]></mch_id>
<nonce_str><![CDATA[1s5m0xlr0y5kys4fgsymv2yqnwx83e8w]]></nonce_str>
<openid><![CDATA[oRULbs81H0Ou_qfHOVpYx_9KVKLM]]></openid>
<out_trade_no><![CDATA[uwx2015072912313419608]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[9FF23318C030E80D406F622847B676AD]]></sign>
<time_end><![CDATA[20150729123121]]></time_end>
<total_fee>4</total_fee>
<trade_type><![CDATA[APP]]></trade_type>
<transaction_id><![CDATA[1000920699201507290500585146]]></transaction_id>
</xml>
     * </pre>
     */
    @ResponseBody
    @RequestMapping(value = "notify")
    public String process(HttpServletRequest request) throws Exception {
        InputStream is = request.getInputStream();
        String xml = Util.inputStreamToString(is);
        return doProcess(xml);
    }

    private String doProcess(String xml) throws IOException, ParserConfigurationException, SAXException {
        if (logger.isDebugEnabled()) {
            logger.debug("notify, xml: " + xml);
        }
        Map<String, Object> map = XMLParser.getMapFromXML(xml);
        String sign = map.get("sign").toString();
        map.remove("sign");
        String mySign = Signature.getSign(map, null);
        
        if (!sign.equals(mySign)) {
            throw new BizException("异步通知签名不正确!");
        }
        
        String orderNo = map.get("out_trade_no").toString();
        
        String returnCode = map.get("return_code").toString();
        if (!"success".equalsIgnoreCase(returnCode)) {
            /*
            onlinePayService.updatePayResult(orderNo, OnlinePayBankStatus.Failed.getValue() + "");
            throw new BizException(map.get("return_msg").toString()); */
        }
        
        String resultCode = map.get("result_code").toString();
        if (!"success".equalsIgnoreCase(resultCode)) {
            /*
            onlinePayService.updatePayResult(orderNo, OnlinePayBankStatus.Failed.getValue() + "");
            throw new BizException(map.get("err_code").toString() + ": " + map.get("err_code_des").toString()); */
        }
        
        
        //onlinePayService.updatePayResult(orderNo, OnlinePayBankStatus.Succeed.getValue() + "");
        
        return successXml;
    }
    
    @RequestMapping("qrCode")
    public String qrCode(HttpServletRequest request,String url, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg"); // 设置返回的文件类型
        ByteArrayOutputStream byteArrayOutputStream = QRCode.from(url)
        .to(ImageType.JPG)
        .withSize(250, 250).stream();
        byteArrayOutputStream.writeTo(response.getOutputStream());
        return null;
    }
    
    public static void main(String[] args) throws Exception {
        String xml = "";
        xml += "<xml><appid><![CDATA[wx28c153b9a6f56a9b]]></appid>";
        xml += "<attach><![CDATA[参与活动]]></attach>";
        xml += "<bank_type><![CDATA[CFT]]></bank_type>";
        xml += "<cash_fee><![CDATA[4]]></cash_fee>";
        xml += "<fee_type><![CDATA[CNY]]></fee_type>";
        xml += "<is_subscribe><![CDATA[N]]></is_subscribe>";
        xml += "<mch_id><![CDATA[1243213602]]></mch_id>";
        xml += "<nonce_str><![CDATA[1s5m0xlr0y5kys4fgsymv2yqnwx83e8w]]></nonce_str>";
        xml += "<openid><![CDATA[oRULbs81H0Ou_qfHOVpYx_9KVKLM]]></openid>";
        xml += "<out_trade_no><![CDATA[uwx2015072912313419608]]></out_trade_no>";
        xml += "<result_code><![CDATA[SUCCESS]]></result_code>";
        xml += "<return_code><![CDATA[SUCCESS]]></return_code>";
        xml += "<sign><![CDATA[9FF23318C030E80D406F622847B676AD]]></sign>";
        xml += "<time_end><![CDATA[20150729123121]]></time_end>";
        xml += "<total_fee>4</total_fee>";
        xml += "<trade_type><![CDATA[APP]]></trade_type>";
        xml += "<transaction_id><![CDATA[1000920699201507290500585146]]></transaction_id>";
        xml += "</xml>";
        new WxPayAsynNotifyController().doProcess(xml);
    }
}
